package de.koller.zero.model;

import de.koller.oceanFramework.util.MIn;
import de.koller.oceanFramework.util.MOut;
import de.koller.zero.ZeroRoot;
import de.koller.zero.arch.ZNode;
import java.io.File;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

public class Realm extends ZNode {
	
	private long round = 0;
	private Map<String, Player> players = new HashMap<>();

	public long getRound() {
		return round;
	}

	public void setRound( long round ) {
		this.round = round;
	}

	public boolean addPlayer( Player player ) {
		if( players.containsKey( player.name ) )
			return false;
		
		players.put( player.name, player );
		this.addNode( player );
		return true;
	}
	
	@Override
	public void generate( ZeroRoot root, Object... references ) {
		super.generate( root, references );
		
		MIn i = new MIn( "./realm/realm.data" );
		round = i.readLong( 1 )[0];
		i.close();
		
		String[] playerNames = new File( "./realm/player/" ).list();
		if( playerNames != null )
				for( String n : playerNames ) {
				String nn = n.replace( ".data", "" );
				addPlayer( new Player( nn ) );
			}
	}

	@Override
	protected void update( Object... refernces ) {
		super.update( refernces );
		
		MOut o = new MOut( "./realm/realm.data" );
		o.writeLong( round );
		o.close();
	}

	@Override
	protected void updateAfter() {
		super.updateAfter();
		
		System.out.println( "Game saved!" );
	}
	
	public int getPlayerNumber() {
		return players.size();
	}

	public Collection<Player> getPlayers() {
		return players.values();
	}
	
}
